/*
    Author:ZhengJiamin
    Date:2020-06-18
    content:user operator
 */
const userDao = require('../dao/userDao');
const md5 = require('../utils/md5/md5');

//1.注册：查询用户的存在性，否则增加
async function addUser(user) {
    var ret = await userDao.findByName(user.name);
    if(ret.success){
        return {success:false,msg:'用户已存在！'};
    }else {
        var data = await userDao.addUser(user);
        //在dao已做数据处理，直接返回
        return data
    }
}
//2.登录：找出用户，然后进行密码比对
//对数据库里的密码进行md5验证，所以数据（密码）一般要进行加密计算（密码验证）
async function login(user) {
    var ret = await userDao.findByName(user.name);
    //找到用户
    if(ret.success){
        var password = md5.toMd5(user.password);
        // console.log(password);
        console.log(ret);
        console.log("pwd:"+password+"--res.pwd:"+ret.password+"--:"+(password==ret.password));
        if(password==ret.user.password){
            return {success:true,user:ret.user};
        }else {
            return {success:false,msg:'用户密码不正确'};
        }
    }else {
        return {success:false,msg:'用户名不存在！'};
    }
};


async function loginCookie(user) {
    var ret = await userDao.findByName(user.name);
    //找到用户
    if(ret.success){
        // var password = md5.toMd5(user.password);
        // console.log(password);
        if(user.password==ret.user.password){
            return {success:true,user:ret.user};
        }else {
            return {success:false,msg:'用户密码不正确'};
        }
    }else {
        return {success:false,msg:'用户名不存在！'};
    }
};

exports.addUser = addUser;
exports.login = login;
exports.loginCookie = loginCookie;